package com.shiwaixiangcun.customer.ui.activity

import android.Manifest
import android.annotation.SuppressLint
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Color
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.text.TextUtils
import android.view.View
import android.view.ViewGroup
import android.widget.FrameLayout
import android.widget.Toast
import com.shiwaixiangcun.customer.ConfigSps
import com.shiwaixiangcun.customer.GlobalApi.DOMAIN_PM
import com.shiwaixiangcun.customer.GlobalApi.merchantUrl
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.app.App
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.AlertJumpServiceDetail
import com.shiwaixiangcun.customer.entity.AlertJumpServiceList
import com.shiwaixiangcun.customer.entity.AlertJunptoBean
import com.shiwaixiangcun.customer.entity.AlertPhoneBean
import com.shiwaixiangcun.customer.interfaces.RequestPermissionType
import com.shiwaixiangcun.customer.module.homeservice.CategoryListActivity
import com.shiwaixiangcun.customer.module.homeservice.ServiceDetailActivity
import com.shiwaixiangcun.customer.ui.dialog.DialogLoginOut
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.DisplayUtil
import com.shiwaixiangcun.customer.utils.JsonUtil.fromJson
import com.shiwaixiangcun.customer.widget.X5WebView
import com.tencent.mm.opensdk.utils.Log
import com.tencent.smtt.export.external.interfaces.JsResult
import com.tencent.smtt.sdk.WebView
import kotlinx.android.synthetic.main.activity_surround_web.*
import kotlinx.android.synthetic.main.toolbar_transparent.*
import java.util.*


/**
 * 周边生活详情(使用WebView展示)
 */
class SurroundWebActivity : BaseActivity() {


    /**
     * 周边生活加载类型
     */
    companion object {
        private const val market = "merchantTypeMarket"
        private const val hotel = "merchantTypeHotel"
        private const val food = "merchantTypeFood"
        private const val scenic = "merchantTypeScenic"
        private const val hospital = "merchantTypeHospital"
        private const val property = "property"
        private const val decorate = "merchantTypeDecorate"

    }

    private var mWebViewType: String? = null
    private var mMerchId: String? = null
    private var mWebUrl: String? = null
    private var mToolbarHeight = 500
    private var phoneNumber: String = ""
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_surround_web)
        initBundleData()
        initWebView()
        initViewAndEvent()
    }


    /**
     * 初始视图
     */
    private fun initViewAndEvent() {
        when (mWebViewType) {
            hospital, property -> {
                val layoutParams = myProgressBar.layoutParams as FrameLayout.LayoutParams
                layoutParams.topMargin = 0
                mTvPageTitle.visibility = View.INVISIBLE

            }
            hotel, scenic, decorate -> {
                setBackColorAndOffset(false)
            }
            food, market -> {
                toolbar.setBackgroundColor(resources.getColor(R.color.ui_white))
                mIvBack.setImageResource(R.mipmap.icon_back_green)
                mTvPageTitle.visibility = View.INVISIBLE
            }
        }
        mIvBack.setOnClickListener { finish() }

        mX5WebView?.setOnScrollChangeListener(object : X5WebView.OnScrollChangeListener {
            override fun onPageEnd(l: Int, t: Int, oldl: Int, oldt: Int) {
            }

            override fun onPageTop(l: Int, t: Int, oldl: Int, oldt: Int) {
            }

            override fun onScrollChanged(l: Int, t: Int, oldl: Int, oldt: Int) {
            }

            override fun scrollDistance(distant: Float) {
                when (mWebViewType) {
                    property, hospital -> {
                        when {
                            distant <= 0 -> {
                                mTvPageTitle.visibility = View.INVISIBLE
                                mIvBack.setImageResource(R.mipmap.icon_back_lwhite)
                                toolbar.setBackgroundColor(Color.argb(0, 227, 29, 26))
                            }
                            distant in 1..mToolbarHeight -> {
                                val scale = distant / mToolbarHeight
                                val alpha: Int = ((255 * scale).toInt())
                                // 只是layout背景透明
                                toolbar.setBackgroundColor(Color.argb(alpha, 255, 255, 255))
                            }
                            else -> {
                                mIvBack.setImageResource(R.mipmap.icon_back_green)
                                mTvPageTitle.visibility = View.VISIBLE
                                toolbar.setBackgroundColor(Color.argb(255, 255, 255, 255))
                            }
                        }
                    }
                    market, food, hotel, scenic -> {
                        when {
                            distant <= 0 -> {
                                mIvBack.setImageResource(R.mipmap.icon_back_green)
                                mTvPageTitle.visibility = View.INVISIBLE
                                toolbar.setBackgroundColor(Color.argb(0, 227, 29, 26))
                            }
                            distant in 1..mToolbarHeight -> {
                                val scale = distant / mToolbarHeight
                                val alpha: Int = ((255 * scale).toInt())
                                // 只是layout背景透明
                                toolbar.setBackgroundColor(Color.argb(alpha, 255, 255, 255))
                            }
                            else -> {
                                mIvBack.setImageResource(R.mipmap.icon_back_green)
                                mTvPageTitle.visibility = View.VISIBLE
                                toolbar.setBackgroundColor(Color.argb(255, 255, 255, 255))
                            }
                        }
                    }
                }
            }
        })

//
    }

    /**
     * 设置箭头颜色以及页面偏移
     */
    private fun setBackColorAndOffset(visible: Boolean) {
        toolbar.setBackgroundColor(resources.getColor(R.color.ui_white))
        if (visible) {
            mTvPageTitle.visibility = View.VISIBLE
        } else {
            mTvPageTitle.visibility = View.INVISIBLE
        }
        val layoutParams = mX5WebView.layoutParams as FrameLayout.LayoutParams
        mIvBack.setImageResource(R.mipmap.icon_back_green)
        layoutParams.topMargin = DisplayUtil.dip2px(this, 56.0f)
    }


    private fun initWebView() {
        mX5WebView?.webChromeClient = object : com.tencent.smtt.sdk.WebChromeClient() {
            override fun onJsAlert(p0: WebView?, p1: String?, message: String?, result: JsResult?): Boolean {

                val bundle = Bundle()
                when {

                //拨打电话
                    message?.contains("phone", true)!! -> {
                        val phoneBean = fromJson<AlertPhoneBean>(message, AlertPhoneBean::class.java)
                        Log.e(BUG_TAG, message)
                        phoneNumber = phoneBean.data.phone
                        showDialog(phoneBean.data.phone)
                        result?.confirm()
                        return true
                    }
                //跳转到“到家服务”列表
                    message.contains("TO_HOME_SERVICE_LIST", true) -> {

                        val fromJson = fromJson<AlertJumpServiceList>(message, AlertJumpServiceList::class.java)

                        bundle.putLong("type", fromJson.data.typeId)
                        bundle.putString("name", fromJson.data.name)
                        readyGo(CategoryListActivity::class.java, bundle)
                        result?.confirm()
                        return true
                    }
                //跳转到”到家服务“详情
                    message.contains("TO_HOME_SERVICE_DETAIL", true) -> {
                        val fromJson = fromJson<AlertJumpServiceDetail>(message, AlertJumpServiceDetail::class.java)
                        if (fromJson.data.detailId != null) {
                            bundle.putLong("serviceId", fromJson.data.detailId)
                            readyGo(ServiceDetailActivity::class.java, bundle)
                        } else {
                            bundle.putLong("type", fromJson.data.typeId)
                            bundle.putString("name", fromJson.data.name)
                            readyGo(CategoryListActivity::class.java, bundle)

                        }
                        result?.confirm()
                        return true
                    }
                //页面跳转
                    message.contains("jumpTo", true) -> {
                        val jumpBean = fromJson<AlertJunptoBean>(message, AlertJunptoBean::class.java)
                        bundle.putString("h5_url", jumpBean.data.url)
                        bundle.putString("h5_name", jumpBean.data.title)
                        if (!TextUtils.isEmpty(jumpBean.data.url)) {
                            readyGo(CommonWebActivity::class.java, bundle)
                        }
                        result?.confirm()
                        return true
                    }
                    else -> {
                        return super.onJsAlert(p0, p1, message, result)
                    }

                }


            }

            /**
             * 设置网页标题
             */
            override fun onReceivedTitle(p0: com.tencent.smtt.sdk.WebView?, p1: String?) {
                super.onReceivedTitle(p0, p1)
                mTvPageTitle.text = p1
                Log.e(BUG_TAG, p1)
            }

            /**
             * 设置网页加载进度监听
             */
            override fun onProgressChanged(p0: com.tencent.smtt.sdk.WebView?, p1: Int) {
                if (p1 == 100) {
                    myProgressBar.visibility = View.GONE
                } else {
                    if (View.INVISIBLE == myProgressBar.visibility) {
                        myProgressBar.visibility = View.VISIBLE
                    }
                    myProgressBar.progress = p1
                }
                super.onProgressChanged(p0, p1)
            }

        }
        mX5WebView?.webViewClient = object : com.tencent.smtt.sdk.WebViewClient() {
            override fun shouldOverrideUrlLoading(view: com.tencent.smtt.sdk.WebView, url: String): Boolean {
                return false
            }


        }

        val siteId = AppSharePreferenceMgr.get(App.getContext(), ConfigSps.CURRENT_SITE_ID, 20) as Int
        val header = HashMap<String, String>()

        header["siteId"] = "" + siteId
        mX5WebView?.loadUrl(mWebUrl, header)
    }


    private fun initBundleData() {
        mMerchId = intent.extras.getString("merchId", "")
        mWebViewType = intent.extras.getString("type")
        //加载物业页面或者其他页面
        mWebUrl = when (mWebViewType) {
        //当前页面为物业
            property -> {
                "$DOMAIN_PM/mi/merchant/property.htm?type=property"
            }
            else -> {
                "$merchantUrl?id=$mMerchId"
            }
        }

    }


    private fun showDialog(phoneNumber: String) {
        val dialogLoginOut = DialogLoginOut(mContext, R.layout.item_dialog_call_phone)
        dialogLoginOut.setTitle("是否要拨打此电话？")
        dialogLoginOut.setMessage(phoneNumber)
        dialogLoginOut.setYesOnclickListener("是", DialogLoginOut.OnPositiveOnclickListener {
            dialogLoginOut.dismiss()
            requestPermission(phoneNumber)
        })

        dialogLoginOut.setNoOnclickListener("否") { dialogLoginOut.dismiss() }
        dialogLoginOut.show()
    }

    private fun requestPermission(number: String?) {
        //判断Android版本是否大于23
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            val checkCallPhonePermission = ContextCompat.checkSelfPermission(this, Manifest.permission.CALL_PHONE)

            if (checkCallPhonePermission != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, arrayOf(Manifest.permission.CALL_PHONE),
                        RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE)
                return
            } else {
                callPhone(number)
            }
        } else {
            callPhone(number)
        }
    }


    /**
     * 注册权限申请回调
     * @param requestCode 申请码
     * @param permissions 申请的权限
     * @param grantResults 结果
     */
    @Override
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        when (requestCode) {
            RequestPermissionType.REQUEST_CODE_ASK_CALL_PHONE -> if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                callPhone(phoneNumber)
            } else {
                // Permission Denied
                Toast.makeText(this, "CALL_PHONE Denied", Toast.LENGTH_SHORT).show()
            }
            else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }
    }

    /**
     * 拨号方法
     */
    @SuppressLint("MissingPermission")
    private fun callPhone(number: String?) {
        val intent = Intent(Intent.ACTION_CALL, Uri.parse("tel:" + number))
        intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
        startActivity(intent)
    }


    override fun finish() {
        val view = window.decorView as ViewGroup
        view.removeAllViews()
        super.finish()
    }
    override fun onDestroy() {

        if (mX5WebView != null) {
            mX5WebView?.loadDataWithBaseURL(null, "", "text/html", "utf-8", null)
            mX5WebView?.clearHistory()

            (mX5WebView?.parent as ViewGroup).removeView(mX5WebView)
            mX5WebView?.destroy()

        }
        super.onDestroy()
    }

}
